const authRoutes = require('./auth');
const tenantRoutes = require('./tenant');

async function routes(fastify, options) {
  // 健康检查端点
  fastify.get('/health', {
    schema: {
      description: 'Health check endpoint',
      tags: ['System'],
      response: {
        200: {
          type: 'object',
          properties: {
            status: { type: 'string' },
            timestamp: { type: 'string' },
            uptime: { type: 'number' },
            version: { type: 'string' },
            environment: { type: 'string' }
          }
        }
      }
    }
  }, async (request, reply) => {
    return {
      status: 'ok',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      version: process.env.npm_package_version || '1.0.0',
      environment: process.env.NODE_ENV || 'development'
    };
  });
  
  // API 信息端点
  fastify.get('/info', {
    schema: {
      description: 'API information endpoint',
      tags: ['System'],
      response: {
        200: {
          type: 'object',
          properties: {
            name: { type: 'string' },
            version: { type: 'string' },
            description: { type: 'string' },
            environment: { type: 'string' },
            features: {
              type: 'object',
              properties: {
                multiTenant: { type: 'boolean' },
                authentication: { type: 'boolean' },
                rateLimit: { type: 'boolean' },
                swagger: { type: 'boolean' }
              }
            },
            endpoints: {
              type: 'object',
              properties: {
                auth: { type: 'string' },
                tenants: { type: 'string' },
                docs: { type: 'string' }
              }
            }
          }
        }
      }
    }
  }, async (request, reply) => {
    return {
      name: 'Multi-Tenant SaaS API',
      version: process.env.npm_package_version || '1.0.0',
      description: 'A scalable multi-tenant SaaS backend built with Fastify',
      environment: process.env.NODE_ENV || 'development',
      features: {
        multiTenant: true,
        authentication: true,
        rateLimit: true,
        swagger: true
      },
      endpoints: {
        auth: '/api/v1/auth',
        tenants: '/api/v1/tenants',
        docs: '/docs'
      }
    };
  });
  
  // 注册测试路由（临时）
  try {
    await fastify.register(require('./test'), { prefix: '/test' });
    fastify.log.info('Test routes registered successfully');
  } catch (error) {
    fastify.log.error('Failed to register test routes:', error.message);
    fastify.log.error('Test routes error stack:', error.stack);
    throw error;
  }
  
  // 注册认证路由
  try {
    await fastify.register(require('./auth'), { prefix: '/auth' });
    fastify.log.info('Auth routes registered successfully');
  } catch (error) {
    fastify.log.error('Failed to register auth routes:', error.message);
    fastify.log.error('Auth routes error stack:', error.stack);
    throw error;
  }
  
  // 注册租户管理路由
  try {
    await fastify.register(require('./tenant'), { prefix: '/tenants' });
    fastify.log.info('Tenant routes registered successfully');
  } catch (error) {
    fastify.log.error('Failed to register tenant routes:', error.message);
    fastify.log.error('Tenant routes error stack:', error.stack);
    throw error;
  }
  
  // 注册用户管理路由
  try {
    await fastify.register(require('./user'), { prefix: '/users' });
    fastify.log.info('User routes registered successfully');
  } catch (error) {
    fastify.log.error('Failed to register user routes:', error.message);
    fastify.log.error('User routes error stack:', error.stack);
    throw error;
  }
  
  // 注册文档路由
  try {
    await fastify.register(require('./docs'));
    fastify.log.info('Docs routes registered successfully');
  } catch (error) {
    fastify.log.error('Failed to register docs routes:', error.message);
    fastify.log.error('Docs routes error stack:', error.stack);
    throw error;
  }
  
  // 404 处理
  fastify.setNotFoundHandler({
    preHandler: fastify.rateLimit()
  }, async (request, reply) => {
    return reply.code(404).send({
      success: false,
      message: 'Route not found',
      error: {
        statusCode: 404,
        path: request.url,
        method: request.method,
        timestamp: new Date().toISOString()
      }
    });
  });
}

module.exports = routes;